Regression with a Categorical Independent Variable
Regression
GLM
Incorporating categorical predictors (i.e., factor variables) into a regression model using dummy variables.
General Principles
To study the relationship between a categorical independent variable and a continuous dependent variable, we use a Categorical model which applies stratification.
Stratification involves modeling how the k different categories of the independent variable affect the target continuous variable by performing a regression for each k category and assigning a regression coefficient for each category. To implement stratification, categorical variables are often encoded using one-hot encoding 🛈 or by converting categories to indices 🛈.
As we generate regression coefficients for each k category, we need to specify a prior with a shape equal to the number of categories k in the code (see comments in the code).
To compare differences between categories, we need to compute the distribution of the differences between categories, known as the contrast distribution. Never compare confidence intervals or p-values directly.
Example
Below is an example of code that demonstrates Bayesian regression with an independent categorical variable using the BayesForge (BF) package. The data consist of one continuous dependent variable (kcal_per_g), representing the caloric value of milk per gram, a categorical independent variable (index_clade), representing species clade membership, and a continuous independent variable (mass), representing the mass of individuals in the clade. The goal is to estimate the differences in milk calories between clades. This example is based on McElreath (2018).
from BayesForge import bf# Setup device------------------------------------------------m = bf(platform='cpu')# Import Data & Data Manipulation ------------------------------------------------data_path = m.load.milk(only_path =True)m.data(data_path, sep=';') m.index(["clade"]) # Convert clade names into indexm.scale(['kcal_per_g', 'mass']) # Scale# Define model ------------------------------------------------def model(kcal_per_g, index_clade, mass): a = m.dist.normal(0, 0.5, shape=(4,), name ='a') # shape based on the number of clades b = m.dist.normal(0, 0.5, shape=(4,), name ='b') s = m.dist.exponential(1, name ='s') mu = a[index_clade] + b[index_clade] * mass m.dist.normal(mu, s, obs=kcal_per_g)# Run mcmc ------------------------------------------------m.fit(model, progress_bar=False) # Optimize model parameters through MCMC sampling# Summary ------------------------------------------------m.summary()
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
bf v 0.0.60 package loaded
jax.local_device_count(cpu) = 32
data(): renamed columns so they can be model arguments: 'kcal.per.g' -> 'kcal_per_g', 'perc.fat' -> 'perc_fat', 'perc.protein' -> 'perc_protein', 'perc.lactose' -> 'perc_lactose', 'neocortex.perc' -> 'neocortex_perc'. The original names are still accepted by the methods of m.
mean
sd
eti89_lb
eti89_ub
ess_bulk
ess_tail
r_hat
mcse_mean
mcse_sd
a[0]
-0.40
0.28
-0.85
0.07
4523.59
3306.20
1.0
0.00
0.00
a[1]
0.24
0.31
-0.26
0.71
3702.17
3540.54
1.0
0.01
0.00
a[2]
0.60
0.30
0.10
1.07
4807.71
2959.68
1.0
0.00
0.00
a[3]
-0.47
0.33
-1.00
0.07
4086.72
3375.67
1.0
0.01
0.00
b[0]
-0.08
0.19
-0.38
0.23
4572.84
3339.12
1.0
0.00
0.00
b[1]
-0.27
0.46
-1.01
0.46
3516.38
2964.29
1.0
0.01
0.01
b[2]
-0.16
0.46
-0.92
0.57
5037.69
3232.46
1.0
0.01
0.01
b[3]
0.23
0.46
-0.51
0.96
4026.17
3425.97
1.0
0.01
0.01
s
0.81
0.12
0.64
1.02
4105.62
2619.89
1.0
0.00
0.00
library(BayesForge)m=importBF(platform='cpu')# Load csv filem$data(m$load$milk(only_path = T), sep=';')m$index(list('clade')) # Convert clade names into indexm$scale(list('kcal_per_g', 'mass')) # Scalem$data_to_model(list('kcal_per_g', 'index_clade', 'mass')) # Send to model (convert to jax array)# Define model ------------------------------------------------model <-function(kcal_per_g, index_clade, mass){# Parameter prior distributions a =bf.dist.normal(0, 0.5, name ='a', shape =c(4L)) # shape based on the number of clades b =bf.dist.normal(0, 0.5, name ='b', shape =c(4L)) s =bf.dist.exponential(1, name ='s') mu = a[index_clade] + b[index_clade] * mass# Likelihoodbf.dist.normal(mu, s, obs=kcal_per_g)}# Run mcmc ------------------------------------------------m$fit(model) # Optimize model parameters through MCMC sampling# Summary ------------------------------------------------m$summary() # Get posterior distributions
usingPyBayesForge# Setup device------------------------------------------------m =importBF(platform="cpu")# Import Data & Data Manipulation ------------------------------------------------data_path = m.load.milk(only_path =true)m.data(data_path, sep=';')m.index("clade") # Convert clade names into indexm.scale(["kcal_per_g", "mass"]) # Scale# Define model ------------------------------------------------@BFfunctionmodel(kcal_per_g, index_clade, mass) a = m.dist.normal(0, 0.5, shape=(4,), name ="a") # shape based on the number of clades b = m.dist.normal(0, 0.5, shape=(4,), name ="b") s = m.dist.exponential(1, name ='s') mu = a[index_clade] + b[index_clade] * mass m.dist.normal(mu, s, obs=kcal_per_g)end# Run mcmc ------------------------------------------------m.fit(model) # Optimize model parameters through MCMC sampling# Summary ------------------------------------------------m.summary() # Get posterior distributions
Caution
For R users, when working with indices you have to ensure 1) that indices are intergers (i.e. as.integer(index_clade)) and, 2) that indices start at 0 (i.e. as.integer(index_clade)-1).
Mathematical Details
Frequentist formulation
We model the relationship between the categorical input feature (X) and the target variable (Y) using the following equation:
Y_i = \alpha + \beta_k X_i + \sigma
Where:
Y_i is the dependent variable for observation i.
\alpha is the intercept term.
\beta_k are the regression coefficients for each k category.
X_i is the encoded categorical input variable for observation i.
\sigma is the error term.
We can interpret \beta_i as the effect of each category on Y relative to the baseline (usually one of the categories or the intercept).
Bayesian formulation
In the Bayesian formulation, we define each parameter with priors 🛈. We can express the Bayesian regression model accounting for prior distributions as follows:
Y \sim \text{Normal}(\alpha + \beta_K X, \sigma)
\alpha \sim \text{Normal}(0,1)
\beta_K \sim \text{Normal}(0,1)
\sigma \sim \text{Exponential}(1)
Where:
Y_i is the dependent variable for observation i.
\alpha is the intercept term, which in this case has a unit-normal prior.
\beta_K are slope coefficients for the K distinct independent variables categories, which also have unit-normal priors.
X_i is the encoded categorical input variable for observation i.
\sigma is a standard deviation parameter, which here has a Exponential prior that constrains it to be positive.
Model validation tests
Comparison with Stan: 2.Categorical variable.py fits the same model with BayesForge and Stan and compares the posterior distributions (KL divergence).
Data generative model and inference model pipeline: 2.Categorical variable.py simulates data from the model with known parameters (data generative model), fits the inference model to each simulated dataset and checks that the parameters are recovered.